<template>
	<view class="container">
		<view class="time-selector">
		    <view class="time-selector-title"> {{ curTime }} 数据时间</view>
			<view
				v-if="timeList!=''" class="time-tabs" style="margin-top: 5px;">
				<view
					:class="[
						'time-tab',
						item.code == curData ? 'active' : '',
					]"
					v-for="(item, index) in timeList"
					:key="index"
					:data-time="item"
					@click="selectTime(item.code)"
				>
					{{ item.name }}
				</view>
			</view>
			<view v-if="curData == 'zidingyi'">
				<uni-datetime-picker type="year-month" fields="month" :end='endTime' :clear-icon="false" v-model="zdyTime" @change='timeChange' />
			</view>
		</view>
		<!-- 车间投用率 -->
		<view class="workshop-rate">
		    <view class="workshop-number">{{ shopValue }} <label style="font-size: 16px;">{{ shopUnit }}</label></view>
		    <view class="workshop-text">{{ shopTitle }}</view>
		</view>
		<kanban-txratio
			:utilData='arealineData'
			:title="titleName.areaLineRatio"
		></kanban-txratio>
		<!-- 图表展示区域 -->
		<view class="chart-section">
		    <view class="chart-header">
		        <view class="chart-title">{{ titleName.arealineTend }}</view>
		    </view>
		<!-- 图表展示区域 -->
		    <view class="chart-header">
				<button class="select-button" @click="openModal('area')">
				    选择对比数据
				</button>
		        <view class="chart-time-selector">
					<uni-datetime-picker v-model="rangeTime" :end='endTime' type="daterange" :clear-icon="false" @change='rangeChange'/>
		        </view>
		    </view>
				<!-- 自定义图例，用于切换显示的系列 -->
				<view class="custom-legend">
					<view class="legend-item" 
						  v-for="item in legendData" 
						  :key="item.index"
						  :class="{ 'active': activeIndexes.includes(item.index) }"
						  @click="toggleSeries(item.index)">
						<view class="legend-dot" :style="{ backgroundColor: item.color }"></view>
						<view class="legend-text">{{ item.name }}</view>
					</view>
				</view>
		    <view class="chart-container" v-if="ableArea">
				<qiun-data-charts
					 :canvas-style="canvasStyle" 
				      type="line"
					  :canvas2d="true"
				      :opts="optsLine"
					  :reshow="isShow"
				      :chartData="lineData"
				    />
			</view>
			<view v-if="!ableArea" style="margin-top: 5px; text-align: center;">
				暂无数据
			</view>
		</view>
		<!-- 图表展示区域 -->
		<view class="chart-section">
		    <view class="chart-header">
		        <view class="chart-title">{{ titleName.areaErrorTend }}</view>
		    </view>
		<!-- 图表展示区域 -->
		    <view class="chart-header">
				<button class="select-button" @click="openModal('errorArea')">
				    选择对比数据
				</button>
		        <view class="chart-time-selector">
					<uni-datetime-picker v-model="rangeerrorTime" :end='endTime' type="daterange" :clear-icon="false" @change='rangeerrorChange'/>
		        </view>
		    </view>
				<!-- 自定义图例，用于切换显示的系列 -->
				<view class="custom-legend" v-if="ableerrorArea" >
					<view class="legend-item" 
						  v-for="item in legenderrorData" 
						  :key="item.index"
						  :class="{ 'active': activeerrorIndexes.includes(item.index) }"
						  @click="toggleerrorSeries(item.index)">
						<view class="legend-dot" :style="{ backgroundColor: item.color }"></view>
						<view class="legend-text">{{ item.name }}</view>
					</view>
				</view>
		    <view class="chart-container" v-if="ableerrorArea">
				<qiun-data-charts
					 :canvas-style="canvasStyle" 
				      type="line"
					  :canvas2d="true"
				      :opts="optserrorLine"
					  :reshow="iserrorShow"
				      :chartData="lineerrorData"
				    />
			</view>
			<view v-if="!ableerrorArea" style="margin-top: 5px; text-align: center;">
				暂无数据
			</view>
		</view>
		<!-- 图表展示区域 -->
		<view class="chart-section">
		    <view class="chart-header">
		        <view class="chart-title">{{ titleName.areazgErrorTend }}</view>
		    </view>
		<!-- 图表展示区域 -->
		    <view class="chart-header">
				<button class="select-button" @click="openModal('zgArea')">
				    选择对比数据
				</button>
		        <view class="chart-time-selector">
					<uni-datetime-picker v-model="rangezgerrorTime" :end='endTime' type="daterange" :clear-icon="false" @change='rangezgerrorChange'/>
		        </view>
		    </view>
				<view class="custom-legend">
					<view class="legend-item" 
						  v-for="item in legendzgerrorData" 
						  :key="item.index"
						  :class="{ 'active': activezgerrorIndexes.includes(item.index) }"
						  @click="togglezgerrorSeries(item.index)">
						<view class="legend-dot" :style="{ backgroundColor: item.color }"></view>
						<view class="legend-text">{{ item.name }}</view>
					</view>
				</view>
		    <view class="chart-container" v-if="ablezgerrorArea">
				<qiun-data-charts
					 :canvas-style="canvasStyle" 
				      type="line"
					  :canvas2d="true"
				      :opts="optszgerrorLine"
					  :reshow="iszgerrorShow"
				      :chartData="linezgerrorData"
				    />
			</view>
			<view v-if="!ablezgerrorArea" style="margin-top: 5px; text-align: center;">
				暂无数据
			</view>
		</view>
		
				<!-- 设备详情弹窗 -->
				<uni-popup ref="popup" type="center" :mask-click="true">
				  <view class="popup-wrapper" style="width: 100vw; height: 100vh; display: flex; justify-content: center; align-items: center;background-color: #ffffff;">
				    <view class="popup-content" style="width: 100%; max-width: 100%;">
				      <view class="modal-header">
		    <view class="modal-title">选择对比数据</view>
		    <button class="close-btn" @click="closeModal()">×</button>
		</view>
				      <view class="modal-body">
				          <!-- 选择区域 -->
						<view class="select-area">
							<view class="area-title">选择项</view>
							 
						<!-- 动态生成选择项 -->
						<view class="condition-group" v-for="(group, groupIndex) in AllData" :key="groupIndex">
							<view class="group-title">{{ group.lineName }}</view>
								<view class="condition-items">
									<view 
									class="condition-item" 
									:class="{selected: isSelected(item.code, item.name)}" 
									@click="toggleSelection(item.code, item.name, item.codeName)"
									v-for="(item, itemIndex) in group.items" 
									:key="itemIndex"
								>
									{{ item.name }}
								</view>
								</view>
						</view> 
						 
					</view>
				          
				          <!-- 已选择区域 -->
		    <view class="selected-area">
		        <view class="area-title">已选择项</view>
		        <view class="selected-items" id="selectedItems">
						        <view v-if="selectedItems.length === 0" class="empty-selected">暂无选择项</view>
						        <view v-else class="selected-tag" v-for="(item, index) in selectedItems" :key="index" @click="removeSelectedItem(item.code, item.name)">
										{{ item.codeName }}
									</view>
						    </view>
		    </view>
				      </view>
				      <view class="modal-footer">
				          <button class="btn btn-cancel" @click="closeModal()">取消</button>
				          <button class="btn btn-confirm" @click="confirmSelection()">确定</button>
				      </view>
				    </view>
				  </view>
				</uni-popup>
	</view>
</template>

<script>
import { timestampFormatDate } from '../../../utils/FormatTime.js'
import { post, postForm } from '@/utils/request';
import { dailyTaskFinishCard, chartTassoGiornalieroCondition, chartTassoGiornaliero, chartErrCount, chartModificaCount} from '@/api/check.js';
export default {
	name: '',
	data() {
        const date = new Date();
        const currentYear = date.getFullYear();
        const currentMonth = date.getMonth() + 1;
        // 格式化当前日期为YYYY-MM格式
        const currentDate = `${currentYear}-${currentMonth.toString().padStart(2, '0')}`;
		return {
			canvasStyle: {
			    zIndex: 1,
			},
			unitName: {
				areaRatio: '',
				areaLineRatio: '',
				warn: '',
				arealineTend: '',
				jkTend: '',
			},
            dateValue: currentDate,
            maxDate: currentDate,
			curTime: Date.now(),
			curData: 'today',
			endTime: Date.now(),
			zdyTime: Date.now(),
			timeList: [
				{
					code: 'today',
					name: '今日'
				},
				{
					code: 'yesterday',
					name: '前一天'
				},
				{
					code: 'zidingyi',
					name: '自定义'
				}
			],
			timeData: {},
			areaData: [],
			arealineData: [],
			equipmentData: [],
			warnTitle: '',
			titleName: {
				areaRatio: '',
				areazgErrorTend: '',
				areaErrorTend: '',
				arealineTend: '',
				jkTend: '',
			},
			curTab: 'ratio',
			tabList: [
				{
					name: '投用率',
					code: 'ratio'
				},
				{
					name: '日*项/月',
					code: 'timeCard'
				}
			],
			originalColors: ["#91CB74","#FAC858","#EE6666","#73C0DE","#3CA272","#FC8452","#9A60B4","#ea7ccc","#66ffff","#ffffbb","#ffb7dd","#096dd9","#ff8888","#b088ff","#ccff99","#ffbb00","#ff44aa","#33ffaa","#ccccff","#ff6666","#66ffcc","#ffcc66","#cc66ff","#66ccff","#ccff66","#ff66cc","#66ff99","#ff9966","#9966ff"], // 原始颜色
			originalerrorColors: ["#91CB74","#FAC858","#EE6666","#73C0DE","#3CA272","#FC8452","#9A60B4","#ea7ccc","#66ffff","#ffffbb","#ffb7dd","#096dd9","#ff8888","#b088ff","#ccff99","#ffbb00","#ff44aa","#33ffaa","#ccccff","#ff6666","#66ffcc","#ffcc66","#cc66ff","#66ccff","#ccff66","#ff66cc","#66ff99","#ff9966","#9966ff"], // 原始颜色
			originalzgerrorColors: ["#91CB74","#FAC858","#EE6666","#73C0DE","#3CA272","#FC8452","#9A60B4","#ea7ccc","#66ffff","#ffffbb","#ffb7dd","#096dd9","#ff8888","#b088ff","#ccff99","#ffbb00","#ff44aa","#33ffaa","#ccccff","#ff6666","#66ffcc","#ffcc66","#cc66ff","#66ccff","#ccff66","#ff66cc","#66ff99","#ff9966","#9966ff"], // 原始颜色
			rangeTime: [Date.now() - 30*24*3600*1000, Date.now()],
			rangeerrorTime: [Date.now() - 30*24*3600*1000, Date.now()],
			rangezgerrorTime: [Date.now() - 30*24*3600*1000, Date.now()],
			lineData: {},
			optsLine: {
			  color: [], // 初始为空，在mounted中设置
			  padding: [8, 20, 20, 10],
			  dataLabel: false,
			  dataPointShape: false,
			  enableScroll: false,
			  legend: {
			      show: false,
			  },
			  xAxis: {
			    disableGrid: true,
			    marginTop: 5,
			    scrollShow: false,
				padding: [0, 20], // 文字自身的上下左右留白 [!code focus]
				offset: 15,         // 轴线距离图表容器底部的距离 [!code focus]
				fontSize: 12,       // 文字大小（影响整体占位）
			    labelCount: 6, // [!code focus]
				gridEval: 5,
				boundaryGap: 'justify'  // 均匀分布模式
			  },
			  yAxis: {
			    gridType: "dash",
			    dashLength: 2
			  },
			  extra: {
			    line: {
			      type: "curve",
			      width: 2,
			      activeType: "hollow",
			    }
			  }
			},
			optserrorLine: {
			  color: [], // 初始为空，在mounted中设置
			  padding: [8, 20, 20, 10],
			  dataLabel: false,
			  dataPointShape: false,
			  enableScroll: false,
			  legend: {
			      show: false,
			  },
			  xAxis: {
			    disableGrid: true,
			    marginTop: 5,
			    scrollShow: false,
				padding: [0, 20], // 文字自身的上下左右留白 [!code focus]
				offset: 15,         // 轴线距离图表容器底部的距离 [!code focus]
				fontSize: 12,       // 文字大小（影响整体占位）
			    labelCount: 6, // [!code focus]
				gridEval: 5,
				boundaryGap: 'justify'  // 均匀分布模式
			  },
			  yAxis: {
			    gridType: "dash",
			    dashLength: 2
			  },
			  extra: {
			    line: {
			      type: "curve",
			      width: 2,
			      activeType: "hollow",
			    }
			  }
			},
			optszgerrorLine: {
			  color: [], // 初始为空，在mounted中设置
			  padding: [8, 20, 20, 10],
			  dataLabel: false,
			  dataPointShape: false,
			  enableScroll: false,
			  legend: {
			      show: false,
			  },
			  xAxis: {
			    disableGrid: true,
			    marginTop: 5,
			    scrollShow: false,
				padding: [0, 20], // 文字自身的上下左右留白 [!code focus]
				offset: 15,         // 轴线距离图表容器底部的距离 [!code focus]
				fontSize: 12,       // 文字大小（影响整体占位）
			    labelCount: 6, // [!code focus]
				gridEval: 5,
				boundaryGap: 'justify'  // 均匀分布模式
			  },
			  yAxis: {
			    gridType: "dash",
			    dashLength: 2
			  },
			  extra: {
			    line: {
			      type: "curve",
			      width: 2,
			      activeType: "hollow",
			    }
			  }
			},
			isShow: false,
			iserrorShow: false,
			iszgerrorShow: false,
			activeIndexes: [0], // 默认激活加热炉曲线
			originalSeriesData: null,
			lineerrorData: {},
			originalSerieserrorData: null,
			activeerrorIndexes: [0],
			linezgerrorData: {},
			originalSerieszgerrorData: null,
			activezgerrorIndexes: [0],
			areaType: '',
			selectedArea: [{ code: '0', name: '车间', codeName: '车间' }],
			selectederrorArea: [{ code: '0', name: '车间', codeName: '车间' }],
			selectedzgerrorArea: [{ code: '0', name: '车间', codeName: '车间' }],
			selectedItems: [{ code: '0', name: '车间', codeName: '车间' }], // 存储已选择的项，默认选中车间
			AllData: [],
			// 添加临时快照变量
			tempSelectedItemsSnapshot: null,
			shopTitle: '',
			shopValue: '',
			shopUnit: '',
			ableArea: true,
			ableerrorArea: true,
			ablezgerrorArea: true,
			
		};
	},
	
	watch: {
	},
	onLoad(option) {
	},
	onShow() {
		this.curTime = Date.now()
		this.zdyTime = Date.now() - 2*24*3600*1000
		this.curTime = timestampFormatDate(this.curTime, 'yyyy-MM-dd')
		this.zdyTime = timestampFormatDate(this.zdyTime, 'yyyy-MM-dd')
		let start = Date.now() - 30*24*3600*1000
		let end = Date.now()
		this.rangeTime = [timestampFormatDate(start, 'yyyy-MM-dd hh:mm:ss'),timestampFormatDate(end, 'yyyy-MM-dd hh:mm:ss')]
		this.rangeerrorTime = [timestampFormatDate(start, 'yyyy-MM-dd hh:mm:ss'),timestampFormatDate(end, 'yyyy-MM-dd hh:mm:ss')]
		this.rangezgerrorTime = [timestampFormatDate(start, 'yyyy-MM-dd hh:mm:ss'),timestampFormatDate(end, 'yyyy-MM-dd hh:mm:ss')]
		this.queryArea()
		this.getRatio()
		this.getareaLine()
		this.getareaerrorLine()
		this.getareazgerrorLine()
	},
	mounted() {
		// 在组件挂载后设置初始颜色
		this.updateChartColors();
		this.updateCharterrorColors();
		this.updateChartzgerrorColors();
	},
	computed: {
		// 获取图例数据
		legendData() {
			if (!this.lineData || !this.lineData.series) return [];
			return this.lineData.series.map((series, index) => {
				return {
					name: series.name,
					color: this.activeIndexes.includes(index) ? this.originalColors[index] : '#CCCCCC',
					index: index
				};
			});
		},
		legenderrorData() {
			if (!this.lineerrorData || !this.lineerrorData.series) return [];
			return this.lineerrorData.series.map((series, index) => {
				return {
					name: series.name,
					color: this.activeerrorIndexes.includes(index) ? this.originalerrorColors[index] : '#CCCCCC',
					index: index
				};
			});
		},
		legendzgerrorData() {
			if (!this.linezgerrorData || !this.linezgerrorData.series) return [];
			return this.linezgerrorData.series.map((series, index) => {
				return {
					name: series.name,
					color: this.activezgerrorIndexes.includes(index) ? this.originalzgerrorColors[index] : '#CCCCCC',
					index: index
				};
			});
		}
	},
	methods: {
		async queryArea() {
			const userInfor = uni.getStorageSync('userInfor');
			const dataParams = {
				userId: userInfor.userId
			}
			const res = await chartTassoGiornalieroCondition(dataParams);
			this.AllData = res.data
		},
		openModal(type) {
			this.areaType = type
			let currentSelectedItems;
			    if(type === 'area') {
			        currentSelectedItems = this.selectedArea
			    } else if(type === 'errorArea') {
			        currentSelectedItems = this.selectederrorArea
			    } else {
			        currentSelectedItems = this.selectedzgerrorArea
			    }
			    
			    // 创建深拷贝快照
			    this.tempSelectedItemsSnapshot = JSON.parse(JSON.stringify(currentSelectedItems));
			    // 设置当前弹窗显示的选择项
			    this.selectedItems = JSON.parse(JSON.stringify(currentSelectedItems));
			this.$refs.popup.open();
		},
		
		closeModal() {
			
			// 使用快照恢复数据
			    if (this.tempSelectedItemsSnapshot) {
			        this.selectedItems = JSON.parse(JSON.stringify(this.tempSelectedItemsSnapshot));
			        this.tempSelectedItemsSnapshot = null;
			    }
			
			this.$refs.popup.close();
		},
		 bindDateChange: function(e) {
		    this.dateValue = e.detail.value
		},
		toggleSelection(code, name, codeName) {
				// 检查该项是否已被选择
				const index = this.selectedItems.findIndex(item => item.code === code && item.name === name);
				if (index > -1) {
					// 如果已选择，则移除
					this.selectedItems.splice(index, 1);
				} else {
					this.selectedItems.push({ code, name, codeName });
				}
				console.log('this.selectedItems', this.selectedItems)
			},
			
			
			// 从已选择项中移除指定项
			removeSelectedItem(code, name) {
			    // 修复：只删除非"车间"的选项
			        const index = this.selectedItems.findIndex(item => item.code === code && item.name === name);
			        if (index > -1) {
			            this.selectedItems.splice(index, 1);
			        }
			},
		
		isSelected(code, name) {
			// 检查该项是否已被选择，用于动态添加selected类
			return this.selectedItems.some(item => item.code === code && item.name === name);
		},
		
		confirmSelection() {
		    // 修复：确认选择时去重
		    // 创建一个新的去重后的数组
		    const uniqueItems = [];
		    const seen = new Set();
			
		    this.selectedItems.forEach(item => {
		        const key = `${item.code}-${item.name}`;
		        if (!seen.has(key)) {
		            seen.add(key);
		            uniqueItems.push(item);
		        }
		    });
			
		    // 更新selectedItems
		    this.selectedItems = uniqueItems;
			
			if(this.areaType === 'area') {
				this.originalSeriesData = null
				this.selectedArea = JSON.parse(JSON.stringify(this.selectedItems))
				if(this.selectedItems.length > 0) {
					this.ableArea = true
				this.getareaLine()
				} else {
					this.ableArea = false
					this.lineData = {}
				}
			} else if(this.areaType === 'errorArea') {
				this.originalSerieserrorData = null
				this.selectederrorArea = JSON.parse(JSON.stringify(this.selectedItems))
				if(this.selectedItems.length > 0) {
					this.ableerrorArea = true
				this.getareaerrorLine()
				} else {
					this.ableerrorArea = false
					this.lineerrorData = {}
				}
			} else {
				this.originalSerieszgerrorData = null
				this.selectedzgerrorArea = JSON.parse(JSON.stringify(this.selectedItems))
				if(this.selectedItems.length > 0) {
					this.ablezgerrorArea = true
				this.getareazgerrorLine()
				} else {
					this.ablezgerrorArea = false
					this.linezgerrorData = {}
				}
			}
			// 确认选择后的处理逻辑
			console.log('已选择的项:', this.selectedItems);
			// 这里可以根据选择的项进行相应的数据处理
			// 处理完成后关闭弹窗
			this.$refs.popup.close();
		},
		selectTime(time) {
			let timeData = ''
			if(time != 'zidingyi') {
				if(time == 'today') {
					timeData = Date.now()
					this.curTime = timestampFormatDate(timeData, 'yyyy-MM-dd')
				} else if(time == 'yesterday') {
					timeData = Date.now() - 1*24*3600*1000
					this.curTime = timestampFormatDate(timeData, 'yyyy-MM-dd')
				}
			} else {
				timeData = this.zdyTime
				this.curTime = timeData
				}
			this.curData = time
			this.getRatio()
		},
		// 切换显示的系列
		toggleSeries(index) {
			// 检查索引是否已在activeIndexes数组中
			let activeIndexes = this.activeIndexes
			const indexPos = activeIndexes.indexOf(index);
			if (indexPos === -1) {
				// 如果不在数组中，添加进去（同时显示）
				activeIndexes.push(index);
			} else {
				// 如果已在数组中，从数组中移除（不再显示）
				activeIndexes.splice(indexPos, 1);
				// 确保至少保留加热炉曲线（索引0）
				if (activeIndexes.length === 0) {
					activeIndexes.push(0);
				}
			this.activeIndexes = activeIndexes
			}
			// 更新图表颜色
			this.updateChartColors();
			// 处理曲线的显示和隐藏
			this.handleSeriesVisibility();
			// 重新渲染图表
			this.isShow = false;
			this.$nextTick(() => {
				this.isShow = true;
			});
		},
		// 切换点检异常显示的系列
		toggleerrorSeries(index) {
			// 检查索引是否已在activeIndexes数组中
			let activeerrorIndexes = this.activeerrorIndexes
			const indexPos = activeerrorIndexes.indexOf(index);
			if (indexPos === -1) {
				// 如果不在数组中，添加进去（同时显示）
				activeerrorIndexes.push(index);
			} else {
				// 如果已在数组中，从数组中移除（不再显示）
				activeerrorIndexes.splice(indexPos, 1);
				// 确保至少保留加热炉曲线（索引0）
				if (activeerrorIndexes.length === 0) {
					activeerrorIndexes.push(0);
				}
			this.activeerrorIndexes = activeerrorIndexes
			}
			// 更新图表颜色
			this.updateCharterrorColors();
			// 处理曲线的显示和隐藏
			this.handleerrorVisibility();
			// 重新渲染图表
			this.iserrorShow = false;
			this.$nextTick(() => {
				this.iserrorShow = true;
			});
		},
		
		// 切换点检异常显示的系列
		togglezgerrorSeries(index) {
			// 检查索引是否已在activeIndexes数组中
			let activezgerrorIndexes = this.activezgerrorIndexes
			const indexPos = activezgerrorIndexes.indexOf(index);
			if (indexPos === -1) {
				// 如果不在数组中，添加进去（同时显示）
				activezgerrorIndexes.push(index);
			} else {
				// 如果已在数组中，从数组中移除（不再显示）
				activezgerrorIndexes.splice(indexPos, 1);
				// 确保至少保留加热炉曲线（索引0）
				if (activezgerrorIndexes.length === 0) {
					activezgerrorIndexes.push(0);
				}
			this.activezgerrorIndexes = activezgerrorIndexes
			}
			// 更新图表颜色
			this.updateChartzgerrorColors();
			// 处理曲线的显示和隐藏
			this.handlezgerrorVisibility();
			// 重新渲染图表
			this.iszgerrorShow = false;
			this.$nextTick(() => {
				this.iszgerrorShow = true;
			});
		},
		// 更新图表颜色
		updateChartColors() {
			this.optsLine.color = this.originalColors.map((color, index) => {
				return this.activeIndexes.includes(index) ? color : '#CCCCCC';
			});
		},
		// 更新图表颜色
		updateCharterrorColors() {
			this.optserrorLine.color = this.originalerrorColors.map((color, index) => {
				return this.activeerrorIndexes.includes(index) ? color : '#CCCCCC';
			});
		},
		updateChartzgerrorColors() {
			this.optszgerrorLine.color = this.originalzgerrorColors.map((color, index) => {
				return this.activezgerrorIndexes.includes(index) ? color : '#CCCCCC';
			});
		},
		// 处理曲线的显示和隐藏
		handleSeriesVisibility() {
			if (!this.lineData || !this.lineData.series) return;
			
			// 保存原始数据的副本，以便恢复
			if (!this.originalSeriesData) {
				this.originalSeriesData = JSON.parse(JSON.stringify(this.lineData.series));
			}
			
			// 深拷贝原始数据，避免直接修改
			const seriesCopy = JSON.parse(JSON.stringify(this.originalSeriesData));
			
			// 根据activeIndexes控制每个系列的显示/隐藏
			this.lineData.series = seriesCopy.map((series, index) => {
				if (this.activeIndexes.includes(index)) {
					// 显示的系列，保持原始数据
					return series;
				} else {
					// 隐藏的系列，将数据设置为空数组
					return {
						...series,
						data: []
					};
				}
			});
		},
		handleerrorVisibility() {
			if (!this.lineerrorData || !this.lineerrorData.series) return;
			
			// 保存原始数据的副本，以便恢复
			if (!this.originalSerieserrorData) {
				this.originalSerieserrorData = JSON.parse(JSON.stringify(this.lineerrorData.series));
			}
			
			// 深拷贝原始数据，避免直接修改
			const seriesCopy = JSON.parse(JSON.stringify(this.originalSerieserrorData));
			
			// 根据activeIndexes控制每个系列的显示/隐藏
			this.lineerrorData.series = seriesCopy.map((series, index) => {
				if (this.activeerrorIndexes.includes(index)) {
					// 显示的系列，保持原始数据
					return series;
				} else {
					// 隐藏的系列，将数据设置为空数组
					return {
						...series,
						data: []
					};
				}
			});
		},
		handlezgerrorVisibility() {
			if (!this.linezgerrorData || !this.linezgerrorData.series) return;
			
			// 保存原始数据的副本，以便恢复
			if (!this.originalSerieszgerrorData) {
				this.originalSerieszgerrorData = JSON.parse(JSON.stringify(this.linezgerrorData.series));
			}
			
			// 深拷贝原始数据，避免直接修改
			const seriesCopy = JSON.parse(JSON.stringify(this.originalSerieszgerrorData));
			
			// 根据activeIndexes控制每个系列的显示/隐藏
			this.linezgerrorData.series = seriesCopy.map((series, index) => {
				if (this.activezgerrorIndexes.includes(index)) {
					// 显示的系列，保持原始数据
					return series;
				} else {
					// 隐藏的系列，将数据设置为空数组
					return {
						...series,
						data: []
					};
				}
			});
		},
		async getRatio() {
			uni.showLoading({
				title: '数据加载中！',
				mask: true,
			});
			const userInfor = uni.getStorageSync('userInfor');
			const dataParams = {
				userId: userInfor.userId,
				queryDate: this.curTime,
				type: 'AREA_LINE'
			}
			const res = await dailyTaskFinishCard(dataParams);
			uni.hideLoading();
			let resData = res.data
			this.shopTitle = resData.workshopName
			this.shopValue = resData.workshopValue
			this.shopUnit = resData.workshopUnit
			this.titleName.areaLineRatio = resData.title
			this.arealineData = resData.listData
		},
		async getareaLine() {
			const userInfor = uni.getStorageSync('userInfor');
			const dataParams = {
				userId: userInfor.userId,
				startTime: this.rangeTime[0],
				endTime: this.rangeTime[1],
				scopeList: this.selectedItems
			}
			const res = await chartTassoGiornaliero(dataParams);
			let resData = res.data
			this.titleName.arealineTend = resData.title
			let dataLength = res.data.categories.length
			if(dataLength > 10) {
				this.optsLine.xAxis.labelCount = 4
			} else if(dataLength == 10) {
				this.optsLine.xAxis.labelCount = 3
			} else {
				this.optsLine.xAxis.labelCount = 6
			}
			let linedata = {
				categories: resData.categories,
				series: resData.series
			}
			// 使用series的长度来初始化activeIndexes，确保所有曲线都显示
			if (resData.series && resData.series.length > 0) {
				this.activeIndexes = Array.from({length: resData.series.length}, (_, i) => i);
				// 更新图表颜色以反映所有系列都处于激活状态
				this.updateChartColors();
			}
			this.confirmDateRange(linedata)
		},
		async getareaerrorLine() {
			const userInfor = uni.getStorageSync('userInfor');
			const dataParams = {
				userId: userInfor.userId,
				startTime: this.rangeerrorTime[0],
				endTime: this.rangeerrorTime[1],
				scopeList: this.selectedItems
			}
			const res = await chartErrCount(dataParams);
			let resData = res.data
			this.titleName.areaErrorTend = resData.title
			let dataLength = res.data.categories.length
			if(dataLength > 10) {
				this.optserrorLine.xAxis.labelCount = 4
			} else if(dataLength == 10) {
				this.optserrorLine.xAxis.labelCount = 3
			} else {
				this.optserrorLine.xAxis.labelCount = 6
			}
			let linedata = {
				categories: resData.categories,
				series: resData.series
			}
			// 使用series的长度来初始化activeIndexes，确保所有曲线都显示
			if (resData.series && resData.series.length > 0) {
				this.activeerrorIndexes = Array.from({length: resData.series.length}, (_, i) => i);
				// 更新图表颜色以反映所有系列都处于激活状态
				this.updateCharterrorColors();
			}
			this.confirmDateerrorRange(linedata)
		},
		
		async getareazgerrorLine() {
			const userInfor = uni.getStorageSync('userInfor');
			const dataParams = {
				userId: userInfor.userId,
				startTime: this.rangezgerrorTime[0],
				endTime: this.rangezgerrorTime[1],
				scopeList: this.selectedItems
			}
			const res = await chartModificaCount(dataParams);
			let resData = res.data
			this.titleName.areazgErrorTend = resData.title
			let dataLength = res.data.categories.length
			if(dataLength > 10) {
				this.optszgerrorLine.xAxis.labelCount = 4
			} else if(dataLength == 10) {
				this.optszgerrorLine.xAxis.labelCount = 3
			} else {
				this.optszgerrorLine.xAxis.labelCount = 6
			}
			let linedata = {
				categories: resData.categories,
				series: resData.series
			}
			// 使用series的长度来初始化activeIndexes，确保所有曲线都显示
			if (resData.series && resData.series.length > 0) {
				this.activezgerrorIndexes = Array.from({length: resData.series.length}, (_, i) => i);
				// 更新图表颜色以反映所有系列都处于激活状态
				this.updateChartzgerrorColors();
			}
			this.confirmDatezgerrorRange(linedata)
		},
		timeChange() {
			this.curTime = this.zdyTime
			this.getRatio()
		},
		rangeChange() {
			this.originalSeriesData = null
			this.getareaLine()
		},
		rangeerrorChange() {
			this.originalSerieserrorData = null
			this.getareaerrorLine()
		},
		rangezgerrorChange() {
			this.originalSerieszgerrorData = null
			this.getareazgerrorLine()
		},
		change() {},
		confirmDateRange(res) {
			this.lineData = JSON.parse(JSON.stringify(res));
			// 保存原始数据并处理曲线显示/隐藏
			this.handleSeriesVisibility();
			this.isShow = true
			this.isShow = false
		},
		confirmDateerrorRange(res) {
			this.lineerrorData = JSON.parse(JSON.stringify(res));
			// 保存原始数据并处理曲线显示/隐藏
			this.handleerrorVisibility();
			// 更新图表颜色配置
			this.updateCharterrorColors();
			this.iserrorShow = true
			this.iserrorShow = false
		},
		confirmDatezgerrorRange(res) {
			this.linezgerrorData = JSON.parse(JSON.stringify(res));
			// 保存原始数据并处理曲线显示/隐藏
			this.handlezgerrorVisibility();
			// 更新图表颜色配置
			this.updateChartzgerrorColors();
			this.iszgerrorShow = true
			this.iszgerrorShow = false
		},

		  
		  closeModal() {
			this.$refs.popup.close();
		  },
	},
}
</script>
<style>
</style>
<style scoped lang="scss">
	.container {
		padding: 12px;
	}
	.uni-tab-title {
		border-bottom: 1px solid rgba(237, 237, 237, 0.9);
	}
	.line-box {
		display: flex;
		.line-item {
			text-align: center;
			padding: 10px;
			border-radius: 1px;
			background: #fff;
			z-index: 1;
			flex: calc(25% - 8px);
	
			&.active {
				background: #ffffff;
				color: #4055e6;
				border-bottom: 2px solid #4055e6;
			}
		}
	}
		/* 车间投用率 */
		.workshop-rate {
		    background: linear-gradient(135deg, #1890ff 0%, #096dd9 100%);
		    border-radius: 12px;
		    padding: 10px;
		    text-align: center;
		    color: white;
		    box-shadow: 0 2px 8px rgba(24, 144, 255, 0.2);
		}
		
		.workshop-number {
		    font-size: 30px;
		    font-weight: 700;
		    margin-bottom: 2px;
		    color: white;
		}
		
		.workshop-text {
		    font-size: 13px;
		    color: white;
		    opacity: 0.9;
		}
	/* 时间筛选器 */
	       .time-selector {
	           background: white;
	           border-radius: 12px;
	           padding: 16px;
	           margin-bottom: 16px;
			   margin-top: 10px;
	           box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
	           border: 1px solid #f0f0f0;
	       }
	
	       .time-selector-title {
	           font-size: 14px;
	           font-weight: 600;
	           color: #262626;
	           margin-bottom: 12px;
	           display: flex;
	           align-items: center;
	       }
	
	       .time-selector-title::before {
	           content: '📅';
	           margin-right: 8px;
	           font-size: 16px;
	       }
	       .uni-input-time {
			   border: 1px solid #e5e5e5;
			   border-radius: 4px;
			   line-height: 35px;
		   }
	       .time-tabs {
	           display: flex;
	           background: #f5f5f5;
	           border-radius: 8px;
	           padding: 4px;
	           gap: 4px;
	       }
	
	       .time-tab {
	           flex: 1;
	           text-align: center;
	           padding: 8px 12px;
	           border-radius: 6px;
	           font-size: 13px;
	           font-weight: 500;
	           color: #8c8c8c;
	           transition: all 0.2s ease;
	           cursor: pointer;
	       }
	
	       .time-tab:active {
	           transform: scale(0.98);
	       }
	
	       .time-tab.active {
			   background: #1890ff;
			   color: white;
			   box-shadow: 0 2px 4px rgba(24, 144, 255, 0.3);
			 }
		/* 自定义图例样式 */
		.custom-legend {
			display: flex;
			flex-wrap: wrap;
			background: white;
		}
		.legend-item {
			display: flex;
			align-items: center;
			cursor: pointer;
			padding: 4px 8px;
			border-radius: 4px;
			transition: all 0.2s;
		}
		.legend-item:active {
			background: #f5f5f5;
		}
		.legend-dot {
			width: 12px;
			height: 12px;
			border-radius: 50%;
			margin-right: 6px;
		}
		.legend-text {
			font-size: 12px;
			color: #333;
		}
		/* 图表区域 */
		.chart-section {
		    background: white;
		    border-radius: 12px;
		    padding: 20px;
			margin-top: 10px;
		    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
		    border: 1px solid #f0f0f0;
		}
		
		.chart-header {
			margin-bottom: 5px;
		}
		
		.chart-title {
		    font-size: 16px;
		    font-weight: 600;
		    color: #333;
		    margin-bottom: 16px;
		}
		
		.chart-title::before {
		    content: '📈';
		    margin-right: 8px;
		}
		
		.chart-time-selector {
		    align-items: center;
		    gap: 8px;
		}
		
		.date-range-picker {
		    display: flex;
		    align-items: center;
		    gap: 4px;
		    background: #f5f5f5;
		    border-radius: 6px;
		    padding: 4px 8px;
		    font-size: 14px;
		    color: #666;
		}
		
		.date-input {
		    border: none;
		    background: transparent;
		    font-size: 11px;
		    color: #666;
		    width: 80px;
		    text-align: center;
		    outline: none;
		}
		
		.date-separator {
		    color: #999;
		    margin: 0 2px;
		}
		
		.date-confirm-btn {
		    background: #1890ff;
		    color: white;
		    border: none;
		    border-radius: 4px;
		    padding: 2px 6px;
		    font-size: 10px;
		    cursor: pointer;
		    margin-left: 4px;
		    transition: all 0.2s ease;
		}
		
		.date-confirm-btn:active {
		    transform: scale(0.95);
		    background: #096dd9;
		}
		
		.chart-container {
		    height: 250px;
		}
		/* 选择按钮 */
		.select-button {
		    width: 100%;
		    padding: 2px 12px;
			margin-top: 10px;
			margin-bottom: 10px;
		    background: linear-gradient(135deg, #1890ff 0%, #096dd9 100%);
		    color: white;
		    border: none;
		    border-radius: 8px;
		    font-size: 14px;
		    font-weight: 600;
		    cursor: pointer;
		    box-shadow: 0 2px 4px rgba(24, 144, 255, 0.2);
		}
		/* 弹框 */
		.popup-wrapper {
		  position: fixed;
		  width: 100vw;
		  height: 100vh;
		  display: flex;
		  justify-content: center;
		  align-items: center;
		  background-color: #ffffff;
		  top: 0;
		  left: 0;
		  z-index: 9999;
		}
		
		.popup-content {
		  width: 100% !important;
		  max-width: 100% !important;
		  height: 100vh;
		  margin: 0;
		  border-radius: 0;
		  display: flex;
		  flex-direction: column;
		}
		.modal-header {
		    padding: 14px 20px;
		    border-bottom: 1px solid #f0f0f0;
		    display: flex;
		    justify-content: center;
		    align-items: center;
		    position: relative;
		}
		
		.modal-title {
		    font-weight: 600;
		    color: #333;
		}
		
		.close-btn {
		    width: 22px;
		    height: 22px;
		    border: none;
		    background: #f5f5f5;
		    border-radius: 50%;
		    cursor: pointer;
		    display: flex;
		    align-items: center;
		    justify-content: center;
		    color: #666;
		    position: absolute;
		    right: 20px;
		}
		
		.modal-body {
		    flex: 1;
		    overflow-y: auto;
		    padding: 14px 14px;
		    -webkit-overflow-scrolling: touch; /* 为iOS设备启用平滑滚动 */
		}
		
		.select-area {
		    margin-bottom: 14px;
		}
		
		.area-title {
		    font-weight: 500;
		    color: #333;
		    margin-bottom: 10px;
		}
		
		.condition-group {
		    margin-bottom: 12px;
		}
		
		.group-title {
		    font-weight: 500;
		    color: #333;
		    margin-bottom: 6px;
		    padding-left: 8px;
		    border-left: 3px solid #1890ff;
		}
		
		.condition-items {
		    display: grid;
		    grid-template-columns: 1fr 1fr 1fr;
		    gap: 5px;
		}
		
		.condition-item {
		    padding: 4px 4px;
		    background: #f8f9fa;
		    border: 1px solid #e9ecef;
		    border-radius: 5px;
		    color: #333;
		    cursor: pointer;
		    text-align: center;
		    font-weight: 500;
		    min-height: 30px;
		    display: flex;
		    align-items: center;
		    justify-content: center;
		}
		
		.condition-item:hover {
		    background: #e6f7ff;
		    border-color: #91d5ff;
		}
		
		.condition-item.selected {
		    background: #1890ff;
		    border-color: #1890ff;
		    color: white;
		    font-weight: 600;
		}
		
		.selected-area {
		    border-top: 1px solid #f0f0f0;
		    padding-top: 14px;
		}
		
		.selected-items {
		    display: flex;
		    flex-wrap: wrap;
		    gap: 5px;
		    min-height: 35px;
		}
		
		.selected-tag {
		    display: flex;
		    align-items: center;
		    gap: 3px;
		    padding: 5px 8px;
		    background: #e6f7ff;
		    color: #1890ff;
		    border-radius: 5px;
		    font-weight: 500;
		    cursor: pointer;
		    transition: background 0.2s;
		    min-height: 24px;
		}
		
		.selected-tag:hover {
		    background: #bae7ff;
		}
		
		.empty-selected {
		    color: #999;
		    text-align: center;
		    padding: 10px;
		}
		
		.modal-footer {
		    padding: 10px 20px;
		    border-top: 1px solid #f0f0f0;
		    display: flex;
		    gap: 10px;
		}
		
		.btn {
		    flex: 1;
		    border: none;
		    border-radius: 5px;
		    font-weight: 500;
		    cursor: pointer;
		}
		
		.btn-cancel {
		    background: #f5f5f5;
		    color: #666;
		}
		
		.btn-confirm {
		    background: #1890ff;
		    color: white;
		}
</style>
